﻿using System;
using System.Web;
using System.Web.Routing;
using LogikBug.ModularMvc.Properties;

namespace LogikBug.ModularMvc.Routing
{
	public class ModularUrlRoutingModule : UrlRoutingModule
	{
		protected override void Init(HttpApplication application)
		{
			application.EndRequest += ReleaseRequestState;
			application.PostResolveRequestCache += PostResolveRequestCache;
		}

		private void ReleaseRequestState(object sender, EventArgs e)
		{
			var application = (HttpApplication)sender;
			var context = application.Context;
			var key = context.Items[Resources.ModularContextSessionKey];

			ReleaseRequestState(key);
		}

		protected void ReleaseRequestState(object key)
		{
			ModularHttpContext.RemoveContext(key);
		}

		private void PostResolveRequestCache(object sender, EventArgs e)
		{
			var application = (HttpApplication)sender;
			PostResolveRequestCache(ModularHttpContext.Create(application.Context));
		}
	}
}